/*
 * @Description:用户的控制层
 * @Version: 2.0
 * @Autor: 黄康辉
 * @Date: 2021-11-17 18:13:46
 * @LastEditors: kafei
 * @LastEditTime: 2021-12-09 16:40:23
 */
const result = require('../utils/result')
const { handleValidator } = require('../utils/validator')
const { filterObj } = require('../utils/index.js')
// const { getJWTPayload } = require('../config/key')
// getUserInfoServer
//
const {
  registerInfoServer,
  loginServer,
  getUserInfoServer,
  upDateUserServer,
  delUserServer,
  getAllUserServer
} = require('../server/userServer')

async function getAllUserController() {
  const data = await getAllUserServer()
  return result('0', { data })
}

async function delUserController(res) {
  const { id } = res
  const data = await delUserServer(id)
  return result('0', { data })
}

// 更新用户数据
async function upDateUserController(res) {
  const keys = [
    'userName',
    'userId',
    'depId',
    'createTime',
    'passWord',
    'rid',
    'telphone',
    'nickName',
    'status',
    'job',
    'isLeave',
    'remarks',
    'id'
  ]
  const target = filterObj(res, keys)
  const data = await upDateUserServer(target)
  return result('0', { data })
}

async function getUserInfoController(token) {
  const data = await getUserInfoServer(token)
  return result('0', { data })
}
/**
 * @description: 注册接口
 * @param {*} userName
 * @param {*} passWord
 * @return {*}{}
 * @author: kafei
 */
async function registerInfoController(cData) {
  const { userName } = cData
  let { passWord } = cData
  if (!passWord) {
    passWord = '123456'
  }
  const target = [
    {
      value: userName,
      pattern: [{ pattern: 'required', message: '姓名字段不能为空' }]
    },
    {
      value: passWord,
      pattern: [{ pattern: 'required', message: '密码不能为空' }]
    }
  ]
  const msg = handleValidator(target)
  if (msg) {
    return result('1', msg)
  }
  const data = await registerInfoServer(cData)
  return data
}

async function loginController({ userName, passWord }) {
  const target = [
    {
      value: userName,
      pattern: [{ pattern: 'required', message: '姓名字段不能为空' }]
    },
    {
      value: passWord,
      pattern: [{ pattern: 'required', message: '密码不能为空' }]
    }
  ]
  const msg = handleValidator(target)
  if (msg) {
    return result('1', msg)
  }
  const data = await loginServer({ userName, passWord })
  return data
}

module.exports = {
  getUserInfoController,
  registerInfoController,
  loginController,
  upDateUserController,
  delUserController,
  getAllUserController
}
